<?php

/**
 * 快报 Keygen
 */

namespace app\lib;

use Ext\libCryptGen;

/**
 * Class keygen
 *
 * @package ext
 */
class KB_keygen extends libCryptGen
{
    /**
     * Obscure Crypt Key
     *
     * @param string $key (32 bits)
     *
     * @return string (40 bits)
     */
    public function obscure(string $key): string
    {
        $unit = str_split($key, 4);

        foreach ($unit as $k => $v) {
            $unit_key = $v[0];

            if ($this->validate_kv($k, $unit_key)) {
                $v = strrev($v);
            }

            $unit[$k] = $v . $unit_key;
        }

        $key = implode($unit);

        unset($unit, $k, $v, $unit_key);
        return $key;
    }

    /**
     * Rebuild Crypt Key
     *
     * @param string $key (40 bits)
     *
     * @return string (32 bits)
     */
    public function rebuild(string $key): string
    {
        $unit = str_split($key, 5);

        foreach ($unit as $k => $v) {
            $unit_key  = substr($v, -1, 1);
            $unit_item = substr($v, 0, 4);

            $unit[$k] = $this->validate_kv($k, $unit_key) ? strrev($unit_item) : $unit_item;
        }

        $key = implode($unit);

        unset($unit, $k, $v, $unit_key, $unit_item);
        return $key;
    }

    /**
     * Validate k & v
     *
     * @param int    $k
     * @param string $v
     *
     * @return bool
     */
    private function validate_kv(int $k, string $v): bool
    {
        return 1 === (($k + (int)$v) & ord($v));
    }
}